package com.gitee.faster.redis.storage;

/**
 * @author hongda.li
 */
@SuppressWarnings("unchecked")
public class CombinedRedisDataStorage implements RedisDataStorage {
    private static final CombinedRedisDataStorage INSTANCE = new CombinedRedisDataStorage();
    private final MemoryRedisDataStorage memoryRedisDataStorage = new MemoryRedisDataStorage();
    private final SqliteRedisDataStorage sqliteRedisDataStorage = new SqliteRedisDataStorage();

    public static CombinedRedisDataStorage getInstance() {
        return INSTANCE;
    }

    @Override
    public <Data> Data query(String name) {
        Object fromMemory = memoryRedisDataStorage.query(name);
        if (fromMemory == null) {
            Object fromSqlite = sqliteRedisDataStorage.query(name);
            if (fromSqlite == null) {
                return null;
            } else {
                memoryRedisDataStorage.store(name, fromSqlite);
                return (Data) fromSqlite;
            }
        }
        return (Data) fromMemory;
    }

    @Override
    public <Data> void store(String name, Data data) {
        memoryRedisDataStorage.store(name, data);
        sqliteRedisDataStorage.store(name, data);
    }

    @Override
    public <Data> Data remove(String name) {
        Data removeFromMemory = this.memoryRedisDataStorage.remove(name);
        Data removeFromSqlite = this.sqliteRedisDataStorage.remove(name);
        return removeFromMemory == null ? removeFromSqlite : removeFromMemory;
    }
}
